#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
""" Interfaz para el firmware de usuario
"""

__version__='0.1'
from bl_fw_interface import *
from usb_interface import *
from util import *

import sys

## comandos de la aplicación
app_comm={ 'APP_BL_REQ':           '\x3D',
           'APP_LED_ON':           '\xB2',
           'APP_LED_OFF':          '\x4E',
           'APP_LED_BLINK':        '\x58',
           'APP_ADC_START':        '\xC0',
           'APP_ADC_STOP':         '\xC2'}

# incluye el byte de ack
expected_len={ 'APP_BL_REQ':           1,
               'APP_LED_ON':           1,
               'APP_LED_OFF':          1,
               'APP_LED_BLINK':        1,
               'APP_ADC_START':        1,
               'APP_ADC_STOP':         1}


handle = None

def obtener_handle ():
    global handle
    # Init the lib!
    cmd('lsmod | grep -q cp210x && sudo rmmod cp210x')

    pdev=DevList('description')
    if pdev<0:
        raise ValueError('No hay dispositivo de interfaz USBXpress')

    open_success, handle = Open(pdev)
    if not open_success:
        raise ValueError('No se puede abrir dispositivo USBXpress')

def app_request (msg):
    global handle
    if handle == None:
        obtener_handle()

    Write(handle, app_comm[msg])
    resp = WaitForRead(handle, expected_len[msg])
    
    if ord(resp[0]) | ord(app_comm[msg]) != 0xFF:
        raise ValueError('Fallo en ack de instruccion: recibi ' + str(ord(resp[0])))
    return resp[1:]

leidos = []

def app_read_uint ():
    global handle
    if handle == None:
        obtener_handle()

    try:
    	while True:
            raw = WaitForRead(handle, 2)
            val = int(raw.encode('hex'), 16)
            leidos.append(val)
    except:
        if len(leidos) == 0:
            return None
        temp = leidos[0]
        leidos.pop(0)
        return temp


def get_mediciones():
    GET_OP = '\xff'
    LEN = 256 * 2
    global handle
    if not handle:
      obtener_handle()

    vals = []
    try:
        Write(handle, GET_OP)
        resp = WaitForRead(handle, LEN)

        if resp is None:
            return []
     
        assert len(resp) == LEN
        for i in range(0, LEN, 2):
            vals.append(int(resp[i:i+2].encode('hex'), 16))
    except Exception, e:
        pass
    return vals
